<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="动物名称" prop="animalName">
        <el-input
          v-model="queryParams.animalName"
          placeholder="请输入动物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属人员" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入所属人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属实验" prop="exName">
        <el-input
          v-model="queryParams.exName"
          placeholder="请输入所属实验"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属课题" prop="topicName">
        <el-input
          v-model="queryParams.topicName"
          placeholder="请输入所属课题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="动物性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择动物性别" clearable>
          <el-option
            v-for="dict in dict.type.gender"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="动物品系" prop="animalStrain">
        <el-select v-model="queryParams.animalStrain" placeholder="请选择动物品系" clearable>
          <el-option
            v-for="dict in dict.type.animal_strain"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="动物类型" prop="animalType">
        <el-select v-model="queryParams.animalType" placeholder="请选择动物类型" clearable>
          <el-option
            v-for="dict in dict.type.animal_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="基因型" prop="genoType">
        <el-select v-model="queryParams.genoType" placeholder="请选择基因型" clearable>
          <el-option
            v-for="dict in dict.type.geno_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker clearable
          v-model="queryParams.birthDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="离乳日期" prop="weaningDate">
        <el-date-picker clearable
          v-model="queryParams.weaningDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择离乳日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="父本动物" prop="parentMaleId">
        <el-input
          v-model="queryParams.parentMaleId"
          placeholder="请输入父本动物"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="母本动物" prop="parentFemaleId">
        <el-input
          v-model="queryParams.parentFemaleId"
          placeholder="请输入母本动物"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属笼位" prop="cageId">
        <el-select v-model="queryParams.cageId" placeholder="请选择所属笼位" clearable>
          <el-option
            v-for="item in cageOptions"
            :key="item.cageId"
            :label="item.cageName"
            :value="item.cageId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入笼资质" prop="certValue">
        <el-select v-model="queryParams.certValue" placeholder="请选择入笼资质" clearable>
          <el-option
            v-for="dict in dict.type.cert_value"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="动物状态" prop="animalStatus">
        <el-select v-model="queryParams.animalStatus" placeholder="请选择动物状态" clearable>
          <el-option
            v-for="dict in dict.type.animal_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['animalManagement:animal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['animalManagement:animal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['animalManagement:animal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['animalManagement:animal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="animalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="动物编号" align="center" prop="animalId" />
      <el-table-column label="动物名称" align="center" prop="animalName" />
      <el-table-column label="所属人员" align="center" prop="userId" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user" :value="scope.row.userId"/>
        </template>
      </el-table-column>
      <el-table-column label="所属实验" align="center" prop="exName" />
      <el-table-column label="所属课题" align="center" prop="topicName" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="动物性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="动物品系" align="center" prop="animalStrain">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.animal_strain" :value="scope.row.animalStrain"/>
        </template>
      </el-table-column>
      <el-table-column label="动物类型" align="center" prop="animalType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.animal_type" :value="scope.row.animalType"/>
        </template>
      </el-table-column>
      <el-table-column label="基因型" align="center" prop="genoType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.geno_type" :value="scope.row.genoType"/>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="周龄" align="center" prop="weekAge">
        <template slot-scope="scope">
          <span>{{ scope.row.weekAge != null ? scope.row.weekAge : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="离乳日期" align="center" prop="weaningDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.weaningDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父本动物" align="center" prop="parentMaleId" />
      <el-table-column label="母本动物" align="center" prop="parentFemaleId" />
      <el-table-column label="所属笼位" align="center" prop="cageId">
          <template slot-scope="scope">
            {{ getCageName(scope.row.cageId) }}
          </template>
      </el-table-column>
      <el-table-column label="入笼资质" align="center" prop="certValue">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cert_value" :value="scope.row.certValue"/>
        </template>
      </el-table-column>
      <el-table-column label="动物状态" align="center" prop="animalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.animal_status" :value="scope.row.animalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown @command="cmd => handleMoreCommand(cmd, scope.row)">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="experiment">参与实验记录</el-dropdown-item>
              <el-dropdown-item command="position">位置变更记录</el-dropdown-item>
              <el-dropdown-item command="feeding">饲养日志</el-dropdown-item>
              <el-dropdown-item command="edit" v-hasPermi="['animalManagement:animal:edit']">修改</el-dropdown-item>
              <el-dropdown-item command="delete" v-hasPermi="['animalManagement:animal:remove']">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改动物档案管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-col :span="12">
          <el-form-item label="动物名称" prop="exName">
            <el-input v-model="form.animalName" placeholder="请输入动物名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属人员" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择所属人员">
                <el-option
                    v-for="dict in dict.type.sys_user"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属实验" prop="exName">
              <el-input v-model="form.exName" placeholder="请输入所属实验" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属课题" prop="topicName">
              <el-input v-model="form.topicName" placeholder="请输入所属课题" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="动物性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择动物性别">
                <el-option
                  v-for="dict in dict.type.gender"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="动物品系" prop="animalStrain">
              <el-select v-model="form.animalStrain" placeholder="请选择动物品系">
                <el-option
                  v-for="dict in dict.type.animal_strain"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="动物类型" prop="animalType">
              <el-select v-model="form.animalType" placeholder="请选择动物类型">
                <el-option
                  v-for="dict in dict.type.animal_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="基因型" prop="genoType">
              <el-select v-model="form.genoType" placeholder="请选择基因型">
                <el-option
                  v-for="dict in dict.type.geno_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker clearable
                v-model="form.birthDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择出生日期">
              </el-date-picker>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="离乳日期" prop="weaningDate">
              <el-date-picker clearable
                v-model="form.weaningDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择离乳日期">
              </el-date-picker>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="父本动物" prop="parentMaleId">
              <el-input v-model="form.parentMaleId" placeholder="请输入父本动物" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="母本动物" prop="parentFemaleId">
              <el-input v-model="form.parentFemaleId" placeholder="请输入母本动物" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属笼位" prop="cageId">
              <el-select v-model="form.cageId" placeholder="请选择所属笼位">
                <el-option
                  v-for="item in cageOptions"
                  :key="item.cageId"
                  :label="item.cageName"
                  :value="item.cageId"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="入笼资质" prop="certValue">
              <el-select v-model="form.certValue" placeholder="请选择入笼资质">
                <el-option
                  v-for="dict in dict.type.cert_value"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="动物状态" prop="animalStatus">
              <el-select v-model="form.animalStatus" placeholder="请选择动物状态">
                <el-option
                  v-for="dict in dict.type.animal_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 参与实验记录对话框 -->
    <el-dialog title="实验记录" :visible.sync="experimentDialog" width="900px" append-to-body>
      <el-table :data="experimentList" v-loading="experimentLoading">
        <el-table-column label="所属人员" prop="userName" align="center" />
        <el-table-column label="所属实验" prop="exName" align="center" />
        <el-table-column label="所属课题" prop="topicName" align="center" />
        <el-table-column label="开始时间" prop="startTime" align="center" />
        <el-table-column label="结束时间" prop="endTime" align="center" />
        <el-table-column label="动物状态" prop="animalStatus" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.animal_status" :value="scope.row.animalStatus" />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="experimentDialog=false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 位置变更记录对话框 -->
    <el-dialog title="位置变更" :visible.sync="positionDialog" width="700px" append-to-body>
      <el-table :data="positionList" v-loading="positionLoading">
        <el-table-column label="笼位位置" prop="position" align="center" />
        <el-table-column label="开始时间" prop="startTime" align="center" />
        <el-table-column label="结束时间" prop="endTime" align="center" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="positionDialog=false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 饲养日志对话框 -->
    <el-dialog title="饲养日志" :visible.sync="feedingDialog" width="900px" append-to-body>
      <el-table :data="feedingList" v-loading="feedingLoading">
        <el-table-column label="记录时间" prop="feedTime" align="center" />
        <el-table-column label="饲养内容" prop="content" align="center" />
        <el-table-column label="数量/用量" prop="quantity" align="center" />
        <el-table-column label="记录人" prop="operator" align="center" />
        <el-table-column label="备注" prop="remark" align="center" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="feedingDialog=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCage } from "@/api/animalManagement/cage";
import { listAnimal, getAnimal, delAnimal, addAnimal, updateAnimal } from "@/api/animalManagement/animal";
import { listAnimalExperiments, listAnimalPositionChanges, listAnimalFeedingLogs } from "@/api/animalManagement/animalExtra";

export default {
  name: "Animal",
  dicts: ['animal_strain', 'geno_type', 'animal_type', 'animal_status', 'cert_value', 'gender','sys_user'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 动物档案管理表格数据
      animalList: [],
      // 弹窗与扩展数据
      experimentDialog: false,
      experimentLoading: false,
      experimentList: [],
      positionDialog: false,
      positionLoading: false,
      positionList: [],
      feedingDialog: false,
      feedingLoading: false,
      feedingList: [],
      // 笼位下拉
      cageOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        animalName: null,
        userName: null,
        exName: null,
        topicName: null,
        source: null,
        gender: null,
        animalStrain: null,
        animalType: null,
        genoType: null,
        birthDate: null,
        weaningDate: null,
        parentMaleId: null,
        parentFemaleId: null,
        cageId: null,
        certValue: null,
        animalStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gender: [
          { required: true, message: "动物性别不能为空", trigger: "change" }
        ],
        animalStrain: [
          { required: true, message: "动物品系不能为空", trigger: "change" }
        ],
        animalType: [
          { required: true, message: "动物类型不能为空", trigger: "change" }
        ],
        animalStatus: [
          { required: true, message: "动物状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.loadCages();
  },
  methods: {
    // 加载笼位下拉选项
    loadCages() {
      const query = { pageNum: 1, pageSize: 1000 };
      listCage(query).then(res => {
        this.cageOptions = (res.rows || []).map(item => ({
          cageId: item.cageId,
          cageName: item.cageName
        }));
      });
    },
    // 根据cageId获取cageName
    getCageName(cageId) {
      if (!cageId) return '-';
      console.log(cageId);
      const cage = this.cageOptions.find(item => item.cageId === cageId);
      return cage ? cage.cageName : cageId;
    },
    /** 查询动物档案管理列表 */
    getList() {
      this.loading = true;
      listAnimal(this.queryParams).then(response => {
        // 增加周龄计算
        const rows = response.rows || [];
        rows.forEach(r => {
          r.weekAge = this.computeWeekAge(r.birthDate);
        });
        this.animalList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 计算周龄 = floor((今天 - 出生日期)/7天)
    computeWeekAge(birthDate) {
      if (!birthDate) return null;
      const bd = new Date(birthDate);
      if (isNaN(bd.getTime())) return null;
      const now = new Date();
      const diffDays = Math.floor((now.getTime() - bd.getTime()) / (24 * 60 * 60 * 1000));
      if (diffDays < 0) return 0;
      return Math.floor(diffDays / 7);
    },
    // 扩展弹窗逻辑
    openExperiment(row) {
      this.experimentDialog = true;
      this.experimentLoading = true;
      listAnimalExperiments(row.animalId).then(res => {
        this.experimentList = res.data || [];
      }).finally(() => {
        this.experimentLoading = false;
      });
    },
    openPositionChange(row) {
      this.positionDialog = true;
      this.positionLoading = true;
      listAnimalPositionChanges(row.animalId).then(res => {
        this.positionList = res.data || [];
      }).finally(() => {
        this.positionLoading = false;
      });
    },
    openFeedingLog(row) {
      this.feedingDialog = true;
      this.feedingLoading = true;
      listAnimalFeedingLogs(row.animalId).then(res => {
        this.feedingList = res.data || [];
      }).finally(() => {
        this.feedingLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        animalId: null,
        animalName: null,
        userId: null,
        userName: null,
        exId: null,
        exName: null,
        topicId: null,
        topicName: null,
        source: null,
        gender: null,
        animalStrain: null,
        animalType: null,
        genoType: null,
        birthDate: null,
        weaningDate: null,
        parentMaleId: null,
        parentFemaleId: null,
        cageId: null,
        certValue: null,
        animalStatus: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.animalId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加动物档案管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const animalId = row.animalId || this.ids
      getAnimal(animalId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改动物档案管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.animalId != null) {
            updateAnimal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnimal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const animalIds = row.animalId || this.ids;
      this.$modal.confirm('是否确认删除动物档案管理编号为"' + animalIds + '"的数据项？').then(function() {
        return delAnimal(animalIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleMoreCommand(cmd, row) {
      switch (cmd) {
        case 'experiment':
          this.openExperiment(row);
          break;
        case 'position':
          this.openPositionChange(row);
          break;
        case 'feeding':
          this.openFeedingLog(row);
          break;
        case 'edit':
          this.handleUpdate(row);
          break;
        case 'delete':
          this.handleDelete(row);
          break;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('animalManagement/animal/export', {
        ...this.queryParams
      }, `animal_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
